//
//  ShareHotView.m
//  phmall
//
//  Created by admin on 2017/12/28.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "ShareHotNewView.h"
#import "ShareListCell.h"
@interface ShareHotNewView ()<UITableViewDelegate,UITableViewDataSource,ShareListCellDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>{
    NSInteger       start;
}
@property(assign,nonatomic)EmptyDataSetType emptyType;
@property(strong,nonatomic)UITableView *myTableview;
@property(strong,nonatomic)NSMutableArray *dataArray;
@property(nonatomic,strong)MBProgressHUD *hud;
@end
@implementation ShareHotNewView
- (instancetype)init
{
    self = [super init];
    if (self) {
        if (@available(iOS 11.0, *)) {
            self.myTableview.estimatedRowHeight = 0;
            self.myTableview.estimatedSectionFooterHeight = 0;
            self.myTableview.estimatedSectionHeaderHeight = 0;
            self.myTableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        [self addSubview:self.myTableview];
        [self.myTableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.offset(0);
        }];
        self.myTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footeRefresh)];
        self.myTableview.mj_footer.hidden=YES;
        self.myTableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HeaderRefresh)];
    }
    return self;
}
-(void)setType:(NSString *)type{
    _type=type;
    start=0;
    [self loadDataWithBuy:YES];
}
-(void)HeaderRefresh{
    start=0;
    [self loadDataWithBuy:NO];
}
-(void)footeRefresh{
    start=self.dataArray.count;
    [self loadDataWithBuy:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShareModel *model=self.dataArray[indexPath.section];
    CGFloat height=model.cellHeight;
    if (model.cellHeight == 0) {
        height=  [ShareListCell calculateHeight:model];
        // 缓存给model
        model.cellHeight = height;
        return height;
    } else {
        return model.cellHeight;
    }
    return height;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0.01;
    }else{
        return 10;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShareListCell *cell=[ShareListCell theShareCellWithTableView:tableView];
    ShareModel *model=self.dataArray[indexPath.section];
    cell.model=model;
    cell.delegate=self;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ShareModel *model=self.dataArray[indexPath.section];
    if (self.delegate && [self.delegate respondsToSelector:@selector(particulars:)]) {
        [self.delegate particulars:model.uid];
    }

}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //分割线补全
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

#pragma mark  DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return nil;
            break;
        case EmptyDataSetNoData:
            
            return [UIImage imageNamed:@"购物车缺省页"];
            break;
        case EmptyDataSetNoNetwork:
            
            return [UIImage imageNamed:@"断网"];
            break;
    }
}
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNone) {
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [activityView startAnimating];
        return activityView;
    }else{
        return nil;
    }
   
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return NO;
            break;
        case EmptyDataSetNoData:
            return YES;
            break;
        case EmptyDataSetNoNetwork:
            return NO;
            break;
    }
    return YES;
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return 0;
}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    
    if (self.emptyType==EmptyDataSetNoData) {
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:@"您的购物车是空的哦！\n跟我去采一些吧。"];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:20],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, 10)];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange(10, 9)];
        return currentPriceStr;
    }
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
        return currentPriceStr;
    }else{
        return nil;
    }
    
}

#pragma mark - DZNEmptyDataSetDelegate

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    start=0;
    [self loadDataWithBuy:YES];
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
}

- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.myTableview.contentOffset = CGPointZero;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray=[[NSMutableArray alloc]init];
    }
    return _dataArray;
}

//MARK:-GETTER
- (UITableView *)myTableview{
    if (!_myTableview) {
        _myTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableview.delegate = self;
        _myTableview.dataSource = self;
        _myTableview.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _myTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableview.showsVerticalScrollIndicator=NO;
        _myTableview.scrollEnabled = YES;
        _myTableview.emptyDataSetSource = self;
        _myTableview.emptyDataSetDelegate = self;
    }
    return _myTableview;
}

- (void)loadDataWithBuy:(BOOL)reload{
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"share"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:[NSString stringWithFormat:@"%ld",start] forKey:@"start"];
    [parametersDic setObject:self.type forKey:@"type"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        if (start==0) {
            [self.dataArray removeAllObjects];
        }
        self.emptyType=EmptyDataSetNoData;
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                NSMutableArray *data=responseDict[@"data"];
             
                if (data.count==0) {
                    [self.myTableview.mj_header endRefreshing];
                    [self.myTableview.mj_footer endRefreshingWithNoMoreData];
                    if (reload) {
                        [self.myTableview reloadData];
                    }
                }else{
                    [self analysisDataWithShareArray:data];
                }
            }
        }
        if (self.delegate && [self.delegate respondsToSelector:@selector(network:)]) {
            [self.delegate network:YES];
        }
        [self.hud hideAnimated:YES];
    } andFailure:^{
        [self.hud hideAnimated:YES];
        if (self.delegate && [self.delegate respondsToSelector:@selector(network:)]) {
            [self.delegate network:NO];
        }
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        }
        self.myTableview.mj_footer.hidden=YES;
        [self.dataArray removeAllObjects];
        self.emptyType=EmptyDataSetNoNetwork;
        [self.myTableview reloadData];
        [self.myTableview.mj_header endRefreshing];
        [self.myTableview.mj_footer endRefreshing];
        
    }];
}
- (void)analysisDataWithShareArray:(NSMutableArray *)array{
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    NSArray *likeArray;
    id obj=[ud objectForKey:@"like"];
    if (obj)
    {
        likeArray=(NSMutableArray *)obj;
    }
    for (NSDictionary *dict in array) {
        ShareModel *model = [ShareModel yy_modelWithDictionary:dict];
        model.like=NO;
        if ([likeArray containsObject:model.uid]) {
            model.like=YES;
        }
        [self.dataArray addObject:model];
    }
    if (self.dataArray.count!=0) {
        self.myTableview.mj_footer.hidden=NO;
    }else{
        self.myTableview.mj_footer.hidden=YES;
    }
    [self.myTableview reloadData];
    [self.myTableview.mj_header endRefreshing];
    [self.myTableview.mj_footer endRefreshing];
}
-(void)likeAction:(UITableViewCell *)cell{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSMutableArray *likeArray=[[NSMutableArray alloc]init];
    id obj=[ud objectForKey:@"like"];
    if (obj)
    {
        for (NSString *str in obj) {
            [likeArray addObject:str];
        }
    }
    
    NSIndexPath *index=[self.myTableview indexPathForCell:cell];
    ShareModel *model=self.dataArray[index.section];
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"share/love"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:model.uid forKey:@"uid"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                NSString *data=responseDict[@"data"];
                if ([data isEqualToString:@"1"]) {
                    if (![likeArray containsObject:model.uid]) {
                        [likeArray addObject:model.uid];
                    }
                    NSArray *like=[NSArray arrayWithArray:likeArray];
                    [ud setObject:like forKey:@"like"];
                    [self loadDataWithBuy:YES];
                }else{
                    NSLog(@"点赞失败");
                }
            }
            
        }
       
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        //        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}
-(void)addFriends:(UITableViewCell *)cell{
    NSIndexPath *index=[self.myTableview indexPathForCell:cell];
    ShareModel *model=self.dataArray[index.section];
    
    if (self.delegate &&[self.delegate respondsToSelector:@selector(addFriends:)]) {
        [self.delegate addFriends:model.uid];
    }

}
-(void)purchase:(UITableViewCell *)cell{
    NSIndexPath *index=[self.myTableview indexPathForCell:cell];
    ShareModel *model=self.dataArray[index.section];
    if (self.delegate && [self.delegate respondsToSelector:@selector(purchase:)]) {
        [self.delegate purchase:model.g_uid];
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
